package cn.itcast.goods.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.StatusConstant;
import cn.itcast.exception.CustomException;
import cn.itcast.exception.DeletionNotAllowedException;
import cn.itcast.goods.dto.SetmealDTO;
import cn.itcast.goods.dto.SetmealPageQueryDTO;
import cn.itcast.goods.mapper.DishMapper;
import cn.itcast.goods.mapper.SetmealDishMapper;
import cn.itcast.goods.mapper.SetmealMapper;
import cn.itcast.goods.pojo.Setmeal;
import cn.itcast.goods.pojo.SetmealDish;
import cn.itcast.goods.service.SetmealService;
import cn.itcast.goods.vo.DishItemVO;
import cn.itcast.goods.vo.SetmealVO;
import cn.itcast.result.PageBean;
import cn.itcast.utils.CheckTextUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;

    /**
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageBean pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {

        // 开启分页
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);

        return PageBean.builder()
                .total(page.getTotal())
                .records(page.getResult())
                .build();
    }

    /**
     * 新增套餐
     *
     * @param setmealDTO
     */
    @Transactional
    @Override
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    public void save(SetmealDTO setmealDTO) {

        String checkText = CheckTextUtils.checkText(setmealDTO.getDescription());
        if (checkText.contains("文本违规")) {
            throw new CustomException(checkText);
        }

        // 拷贝属性值
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);


        // 默认新增套餐为停售状态
        setmeal.setStatus(StatusConstant.DISABLE);



        setmealMapper.insert(setmeal);

        // 将套餐菜品关系信息批量插入
        setmealDTO.getSetmealDishes().forEach(e -> {
            e.setSetmealId(setmeal.getId());
            setmealDishMapper.insert(e);
        });
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getById(Long id) {
        return setmealMapper.getById(id);
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {

        // 判断要删除的套餐中是否有正在售卖的套餐
       if (setmealMapper.getByIdsAndStatus(ids, StatusConstant.ENABLE).size() > 0) {
           // 有套餐正在售卖，不能删除
           throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        setmealMapper.deleteByIds(ids);
        setmealDishMapper.deleteBySetmealIds(ids);
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @Transactional
    @Override
    public void update(SetmealDTO setmealDTO) {

        String checkText = CheckTextUtils.checkText(setmealDTO.getDescription());
        if (checkText.contains("文本违规")) {
            throw new CustomException(checkText);
        }

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);


        setmealMapper.update(setmeal);

        // 清空对应套餐id的全部套餐菜品关系记录
        List<Long> ids = new ArrayList<>();
        ids.add(setmeal.getId());
        setmealDishMapper.deleteBySetmealIds(ids);

        // 批量添加对应套餐id的餐菜品关系记录
        setmealDTO.getSetmealDishes().forEach(e -> {
            e.setSetmealId(setmeal.getId());
            setmealDishMapper.insert(e);
        });
    }

    /**
     * 套餐起售停售
     *
     * @param status
     * @param id
     */
    @CacheEvict(cacheNames = "setmeal", allEntries = true)
    @Override
    public void startOrStop(Integer status, Long id) {
        if (status == StatusConstant.ENABLE) {
            List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);


            List<Long> ids = setmealDishes.stream()
                    .map(e -> e.getDishId())
                    .collect(Collectors.toList());

            if (dishMapper.getByIdsAndStatus(ids, StatusConstant.DISABLE).size() > 0) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }


        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }

    /**
     * 根据分类id查询套餐
     *
     * @param categoryId
     * @return
     */
    @Cacheable(cacheNames = "setmeal:list", key = "#categoryId")
    @Override
    public List<Setmeal> list(Long categoryId) {
        return setmealMapper.getByCategoryId(categoryId);
    }

    /**
     * 根据套餐id查询包含的菜品
     *
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "setmeal:getByIdWidthDish", key = "#id")
    @Override
    public List<DishItemVO> getByIdWidthDish(Long id) {
        return setmealMapper.getByIdWidthDishItemVO(id);
    }


}
